/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.github.florent37.camerafragment.sample.rxbus;

import io.reactivex.rxjava3.core.Scheduler;
import io.reactivex.rxjava3.schedulers.Schedulers;
import ohos.app.AbilityContext;
import ohos.app.dispatcher.TaskDispatcher;

import java.util.concurrent.Executor;

/**
 * 定制分发事件
 *
 * @since 2021-03-18
 */
public class HarmonySchedulers implements Executor {
    private static HarmonySchedulers instance;
    private static AbilityContext sAbility;
    private Scheduler mMainScheduler;
    private TaskDispatcher uiTaskDispatcher;
    private long delayTime = 0L;

    private HarmonySchedulers() {
        mMainScheduler = Schedulers.from(this);
    }

    /**
     * 获取主线程
     *
     * @param ability 页面
     * @return Scheduler 主线程执行者
     */
    public static synchronized Scheduler mainThread(AbilityContext ability) {
        sAbility = ability;
        if (instance == null) {
            instance = new HarmonySchedulers();
        }
        return instance.mMainScheduler;
    }

    @Override
    public void execute(Runnable runnable) {
        if (uiTaskDispatcher == null) {
            uiTaskDispatcher = sAbility.getUITaskDispatcher(); // 注意，这里要用Ability来获取UI线程的任务发射器，Ability自己想办法获取
        }
        uiTaskDispatcher.delayDispatch(runnable, delayTime);
    }
}
